import csv
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn


def write_csv_to_docx(csv_path, docx_path):
    # 创建 Word 文档对象
    doc = Document()
    # 设置字体为宋体（表格内容）
    def set_cell_font(cell, text, font_size=10.5):
        run = cell.paragraphs[0].add_run(text)
        run.font.name = '宋体'
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        run.font.size = Pt(font_size)
    # 打开 CSV 文件
    with open(csv_path, 'r', encoding='utf-8-sig') as f:
        reader = list(csv.reader(f))
        if not reader:
            print("CSV 文件为空")
            return
        # 创建表格（行数，列数）
        table = doc.add_table(rows=len(reader), cols=len(reader[0]))
        table.style = 'Table Grid'
        # 填充表格内容
        for row_idx, row in enumerate(reader):
            for col_idx, cell_value in enumerate(row):
                cell = table.cell(row_idx, col_idx)
                set_cell_font(cell, cell_value, font_size=10.5)
    # 保存 Word 文件
    doc.save(docx_path)
    print(f"✅ 表格已写入：{docx_path}")


# 示例使用
csv_file = r"D:\hbyt\AI智能投标\markdown_output\media\激励及绩效管理_v1.0_2201\tables\table_0.csv"
output_docx = r"D:\hbyt\output_table.docx"
write_csv_to_docx(csv_file, output_docx)
